/** @jsxImportSource @emotion/react */
import * as React from "react";
import {css} from "@emotion/react";
import {
    Text, BlobInputList, CCell, Table, TableHead, TableRow, TableBody, InputLine, Select, Button,
} from "customize-easy-ui-component";
import {InspectRecordLayout, InternalItemProps, RepLink, useItemInputControl,} from "../../common/base";
import {useMeasureInpFilter} from "../../common/hooks";
import {calcAverMaxArrObj, floatInterception, objNestSet, tableSetInp} from "../../../common/tool";
import {useOmnipotentPref, useOmnipotentPrefTitle} from "../../hook/useOmnipotentPref";

//name:不能乱改，下面的处理函数关联存储名字了！
export const items制动距 = [
    ['前进往', [ {t:'3.5(3)',s: 6} ], '空载前进行车制动（往）', ],
    ['前进返', [{}], '空载前进行车制动（返）', ],
    ['前进均', [{}], '空载前进行车制动平均值' ],
    ['后退往', [{}], '空载后退行车制动（往）' ],
    ['后退返', [{}], '空载后退行车制动（返）' ],
    ['后退均', [{}], '空载后退行车制动平均值' ],
];

const tailText=<Text css={{display: 'grid',fontSize: '0.8rem'}}>
    <Text css={{textIndent: '2.4rem',fontSize: '0.8rem'}}></Text>
</Text>;
export const itemA制动距: string[] = ['组别' ];
items制动距.forEach(([name, title, initIsp], i: number) => {
    itemA制动距.push(name as string);
});
interface Props extends InternalItemProps {
    config: any[];
}
// const defaultValCb= (par: any)=>{
//     const { 前进往,前进返,后退往,后退返 }=par||{};
//     if(前进往 || 前进返){
//         let [s,_]=calcAverMaxArrObj([前进往,前进返],(row)=>row?.s,2,2);
//         par.前进均={s };
//     }
//     return  par;
// }
//【较麻烦】 if('前进往'===name){
//     let [s,_]=calcAverMaxArrObj([{s:v},inp.前进返],(row)=>row?.s,2,2);
//     objNestSet('前进均', 's', s || undefined, inp, setInp);
//     setInp({...inp,[field]:{...inp?.[field] , [sub]: txt || undefined} });
// }
// React.useEffect(() => {      #单只能适用：平均值不会被人工去修改的场景。会造成歧义问题； 【问题】不晓得是否真的刚刚修改，还是初始化的。
//   if(inp) {       //inp=null死循环
//             let [s, _] = calcAverMaxArrObj([inp?.前进往, inp?.前进返], (row) => row?.s, 2, 2);
//             setInp({...inp, 前进均: {...inp?.前进均, s}});
//         }
//     }, [inp?.前进往?.s, setInp]
// );
function calcDistanceA1(v: number){
    let bk;
    if(v<=5) bk= 0.15*v + v*v/23.6;
    else if(v<=13.4) bk= 0.15*v + v/4.7;
    else bk= 0.15*v + v*v/63.6;
    return floatInterception(bk, 3);
}
function calcDistanceA2(v: number){
    let bk;
    if(v<=5) bk= 0.15*v + v*v/19.1;
    else if(v<=13.4) bk= 0.15*v + v/3.8;
    else bk= 0.15*v + v*v/50.9;
    return floatInterception(bk, 3);
}
function calcDistanceC(v: number){
    let bk;
    if(v<=4) bk= 0.15*v + v*v/11.4;
    else if(v<=13.4) bk= 0.15*v + v/2.8;
    else bk= 0.15*v + v*v/38.1;
    return floatInterception(bk, 3);
}
export const Braking =
    React.forwardRef((
        {children, show, alone = true, refWidth, label='附录A: 制动距离检测', config}: Props, ref
    ) => {
        const {inp, setInp} = useItemInputControl({ref});
        const [getInpFilter] = useMeasureInpFilter(null, itemA制动距, );
        const titNode=useOmnipotentPrefTitle({config: config, });
        function modifySpeed(n:string, val: string|undefined){
            if('前进往'===n){
               let [s, _] = calcAverMaxArrObj([{s:val}, inp?.前进返], (row) => row?.s, 2, 2);
                setInp({...inp, 前进均: {...inp?.前进均, s}, 前进往: {...inp?.前进往, s:val}});
            }
            else if('前进返'===n){
                let [s, _] = calcAverMaxArrObj([{s:val}, inp?.前进往], (row) => row?.s, 2, 2);
                setInp({...inp, 前进均: {...inp?.前进均, s}, 前进返: {...inp?.前进返, s:val}});
            }
            else if('后退往'===n){
                let [s, _] = calcAverMaxArrObj([{s:val}, inp?.后退返], (row) => row?.s, 2, 2);
                setInp({...inp, 后退均: {...inp?.后退均, s}, 后退往: {...inp?.后退往, s:val}});
            }
            else if('后退返'===n){
                let [s, _] = calcAverMaxArrObj([{s:val}, inp?.后退往], (row) => row?.s, 2, 2);
                setInp({...inp, 后退均: {...inp?.后退均, s}, 后退返: {...inp?.后退返, s:val}});
            }
            else objNestSet(n, 's', val || undefined, inp, setInp);
        }
        function modifyDistance(n:string, val: string|undefined){
            if('前进往'===n){
                let [b, _] = calcAverMaxArrObj([{b:val}, inp?.前进返], (row) => row?.b, 2, 2);
                setInp({...inp, 前进均: {...inp?.前进均, b}, 前进往: {...inp?.前进往, b:val}});
            }
            else if('前进返'===n){
                let [b, _] = calcAverMaxArrObj([{b:val}, inp?.前进往], (row) => row?.b, 2, 2);
                setInp({...inp, 前进均: {...inp?.前进均, b}, 前进返: {...inp?.前进返, b:val}});
            }
            else if('后退往'===n){
                let [b, _] = calcAverMaxArrObj([{b:val}, inp?.后退返], (row) => row?.b, 2, 2);
                setInp({...inp, 后退均: {...inp?.后退均, b}, 后退往: {...inp?.后退往, b:val}});
            }
            else if('后退返'===n){
                let [b, _] = calcAverMaxArrObj([{b:val}, inp?.后退往], (row) => row?.b, 2, 2);
                setInp({...inp, 后退均: {...inp?.后退均, b}, 后退返: {...inp?.后退返, b:val}});
            }
            else objNestSet(n, 'b', val || undefined, inp, setInp);
        }
        function calcJustify(){
            if('A1'===inp?.组别){
                let p1=calcDistanceA1(inp?.前进均?.s);
                let p2=calcDistanceA1(inp?.后退均?.s);
                setInp({...inp, 前进均: {...inp?.前进均, p:p1}, 后退均: {...inp?.后退均, p:p2} });
            }
            else if('A2'===inp?.组别){
                let p1=calcDistanceA2(inp?.前进均?.s);
                let p2=calcDistanceA2(inp?.后退均?.s);
                setInp({...inp, 前进均: {...inp?.前进均, p:p1}, 后退均: {...inp?.后退均, p:p2} });
            }
            else if('C'===inp?.组别){
                let p1=calcDistanceC(inp?.前进均?.s);
                let p2=calcDistanceC(inp?.后退均?.s);
                setInp({...inp, 前进均: {...inp?.前进均, p:p1}, 后退均: {...inp?.后退均, p:p2} });
            }
        }
        return (
            <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                                 alone={alone} label={label!}>
                <Text variant="h5">{label}：</Text>
                <InputLine  label='车辆组别:' >
                    <Select inputSize="md" css={{minWidth:'140px',fontSize:'1.3rem',padding:'0 1rem'}}
                            value={ inp?.组别  ||''}
                            onChange={e => setInp({ ...inp, 组别: e.currentTarget.value||undefined}) }
                    >
                        <option></option>
                        <option>A1</option>
                        <option>A2</option>
                        <option>C</option>
                    </Select>
                </InputLine>
                <hr/>
                {config.map(([name, _1, _2, unit]: any, i: number) => {
                    return (<React.Fragment key={i}>
                        <div css={{display: 'flex', flexWrap: 'wrap', alignItems: 'center'}}>
                            {titNode[i]}&nbsp;
                            <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                                车辆速度：
                                <BlobInputList value={inp?.[name]?.s || ''}  rows={1}
                                               style={{display: 'inline-flex', width: '6rem', maxWidth: '100%', fontSize: '1.1rem',}}
                                               listStyle={css({fontSize: '1.4rem',})}
                                               onListChange={v =>{
                                                   modifySpeed(name,v);
                                               }}/>
                                （km/h）
                            </div>
                            <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                                制动距离：
                                <BlobInputList value={inp?.[name]?.b || ''}  rows={1}
                                               style={{display: 'inline-flex', width: '6rem', maxWidth: '100%',}}
                                               onListChange={v => modifyDistance(name,v)}/>
                                （m）
                            </div>
                            <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                                判断标准：
                                <BlobInputList value={inp?.[name]?.p || ''} datalist={[]} rows={1}
                                               style={{display: 'inline-flex', width: '11rem', maxWidth: '100%',}}
                                               onListChange={v => objNestSet(name, 'p', v || undefined, inp, setInp)}/>
                                （m）
                            </div>
                            <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                                检验结果：
                                <BlobInputList value={inp?.[name]?.r || ''} datalist={['√', '／', '×']} rows={1}
                                               style={{display: 'inline-flex', width: '8rem', maxWidth: '100%', fontSize: '1.1rem',}}
                                               listStyle={css({fontSize: '1.4rem',})}
                                               onListChange={v => objNestSet(name, 'r', v || undefined, inp, setInp)}/>
                            </div>
                        </div>
                    </React.Fragment>);
                })}
                <Button intent="danger" disabled={!inp?.组别 || (!inp?.前进均?.s && !inp?.后退均?.s) }
                        onPress={async () => await calcJustify()}
                >判断标准计算</Button>
                {children ? children :
                    <>{tailText}</>
                }
            </InspectRecordLayout>
        );
});

const tailRender = (orc: any, name: string) => <>
    <CCell>{orc?.[name]?.s ?? '／'}</CCell>
    <CCell>{orc?.[name]?.b ?? '／'}</CCell>
    <CCell>{orc?.[name]?.p ?? '／'}</CCell>
    <CCell><Text css={{fontSize: '1.05rem'}}>{orc?.[name]?.r ?? '／'}</Text></CCell>
</>;
export const BrakingVw = ({orc, rep, label = '附录A: 制动距离检测', config, children}
                     : { orc: any, rep: any, label?: any, config: any[], children?: React.ReactNode }
) => {
    const [renders]=useOmnipotentPref({orc, config:config, tailRender,pcols:2,noNo:true});
    return <>
        <div css={{"@media print": {paddingBottom: '5.5rem', pageBreakInside: 'avoid'}}}>
            <Text variant="h4" css={{marginTop: '1rem',}}>{label}</Text>
            <Text>车辆组别: &nbsp; {orc.组别}</Text>
        </div>
        <Table id='Braking' fixed={ ["3%", "4%", "%", "17%", "15%", "14.5%","9%"] }
               tight  miniw={800} css={ {borderCollapse: 'collapse', "@media print": {marginTop: '-5.5rem'}} } >
            <TableHead>
                <TableRow>
                    <CCell colSpan={2}><Text css={{fontSize:'0.7rem'}}>项目编号</Text></CCell><CCell>检验内容</CCell>
                    <CCell><Text css={{fontSize:'0.8rem'}}>车辆速度（km/h）</Text></CCell>
                    <CCell>制动距离（m）</CCell><CCell>判断标准（m）</CCell><CCell>检验结果</CCell>
                </TableRow>
            </TableHead>
            <TableBody>
                <RepLink ori rep={rep} tag={'Braking'}>
                    {renders}
                </RepLink>
            </TableBody>
        </Table>
        {children ? children :
            <>{tailText}</>
        }
    </>;
};
